﻿using Autofac.Integration.WebApi;
using CNKI.TPI.Web.Admin.IBLL;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Interface.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.Model;
using System.Text.RegularExpressions;

namespace CNKI.TPI.Web.Interface.Areas.User.Controllers
{
    enum ActionType
    {
        search = 0,
        download = 1,
        view = 2
    }
    public class UploadUserActionController : BaseApiController
    {
        private INaviService naviService = null;
        public UploadUserActionController(INaviService naviService)
        {
            this.naviService = generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
        }

        public object Post()
        {
            OutputEntity result = new OutputEntity();
            try
            {
                HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"];//获取传统context     
                HttpRequestBase request = context.Request;//定义传统request对象
                string action = request.Form["action"];
                string dbcode = request.Form["dbCode"];
                string value = request.Form["value"];
                string userid = request.Form["userid"];
                string usercode = request.Form["usercode"];

                SYS_CMS_DATABASE dbInfo = naviService.GetDatabase(dbcode, 0);

                if (dbInfo == null || dbInfo.SysID == 0)
                {
                    result.Status = Status.Error;
                    return result;
                }

                string sql = @"INSERT INTO tpi.sysoperatelog
                                (Thread,UserID,UserName,Level,OperateTime,OperateClass,OperateFunc,InParameter,OutParameter,Type,Elapsed,Memo,Exception,IP)
                                VALUES
                                (0,'{0}','{1}','INFO','{2}','{3}','{4}','{5}','',0,0,'','','{6}')";
                bool status = false;
                switch ((ActionType)int.Parse(action))
                {
                    case ActionType.search:
                        sql = string.Format(sql, userid, usercode, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), "SearchService", "SingleSearch", "dbID=\\'" + dbInfo.SysID + "\\'|searchQuery=\\'" + value + "\\'|dbName=\\'" + dbcode + "\\'|", IPUntil.GetIP());
                        if (!string.IsNullOrEmpty(sql))
                        {
                            AutofacWebApiDependencyResolver dependencyResolver = (AutofacWebApiDependencyResolver)GlobalConfiguration.Configuration.DependencyResolver;
                            IDataContext dataContext = (IDataContext)dependencyResolver.GetService(typeof(IDataContext));
                            status = dataContext.ExecuteNonQuery(sql, "mysql");
                        }
                        break;
                    case ActionType.download:
                        LogOpr.Download(dbInfo.SysID.ToString(), dbcode, value, value, (int)BrowseFromType.InterfaceBrowse, userid, usercode);
                        status = true;
                        break;
                    case ActionType.view:
                        LogOpr.Browse(dbInfo.SysID.ToString(), dbcode, value, (int)BrowseFromType.InterfaceBrowse, userid, usercode);
                        status = true;
                        break;
                    default:
                        break;
                }

                if (status)
                {
                    result.Status = Status.Success;
                }
                else
                {
                    result.Status = Status.Error;
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
                result.Status = Status.Error;
                result.message = ex.Message;
            }
            return result;
        }

        private string GetIP(HttpRequestBase request)
        {
            string result = String.Empty;

            result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }

            if (null == result || result == String.Empty || !IsIP(result))
            {
                return "0.0.0.0";
            }

            return result;
        }

        /// <summary>
        /// 是否为ip
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        private bool IsIP(string ip)
        {
            return Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
    }
}
